﻿using System.Windows.Input;
using DevExpress.Mvvm;
using EduAssess.Models;
using EduAssess.Services;

namespace EduAssess.ViewModels;

public abstract class CreateTestPageViewModel(TestService testService, TestState testState) : BindableBase
{
    public Test? Test { get; } = testState.CurrentTest;

    public ICommand SaveTestCommand => new DelegateCommand(() => { testService.SaveTest(Test); });
    public ICommand DeleteTestCommand => new DelegateCommand(() => { testService.DeleteTest(Test.Id); });

    public ICommand AddQuestionCommand => new DelegateCommand(() =>
    {
        var question = new Question
        {
            Name = "New Question"
        };
        Test.Questions.Add(question);
    });

    public ICommand DeleteQuestionCommand => new DelegateCommand<Guid>(id =>
    {
        var obj = Test.Questions.FirstOrDefault(x => x.Id == id);
        Test.Questions.Remove(obj!);
    });

    public ICommand DeleteAnswerCommand => new DelegateCommand<Guid>(id =>
    {
        foreach (var question in Test.Questions)
        {
            foreach (var answer in question.Answers)
            {
                if (answer.Id != id) continue;
                question.Answers.Remove(answer);
                break;
            }
        }
    });

    public ICommand AddAnswerCommand => new DelegateCommand<Guid>((questionId) =>
    {
        var question = Test.Questions.FirstOrDefault(x => x.Id == questionId);
        var answer = new Answer
        {
            Name = "New Answer"
        };
        question!.Answers.Add(answer);
    });
}